<?php
use com\gdl\kq\dataobject\attendancegroup\AttendanceGroupDTO;
use com\gdl\common\dataobject\common\ResultDO;
use com\gdl\kq\interfaces\AttAdminAttendanceGroupServiceIf;
/**
 *  考勤
 *  @author gdl
 */
class api_AttAdminAttendanceGroupService extends api_Abstract implements AttAdminAttendanceGroupServiceIf
{
    /**
     * 给考勤组赋予权限
     * @param int $id 考勤组ID
     * @param int $UnitsId 上级单位ID
     * @param array $userId 当前adminUserId
     * @param array $hisUser
     * @return bool
     */
    public function userUnitsAssoc($id = 0, $UnitsId, $userId = [0], $hisUser = [0])
    {
        if (!$id || empty($userId)) {
            return true;
        }
        $UnitsId = intval($UnitsId);
        $appadminuser = new model_lhbase_appadminuser();
        $units = new model_lhbase_units();
        $authuserunits = new model_lhbase_authuserunits();
        $adminUserIdgroupId = new model_attendance_adminuserattendancegroup();
        $userUnitsId = $authuserunits->select('unitsId=' . $UnitsId . ' and adminUserId in(' . implode(',', $userId) . ')', 'adminUserId')->items;
        if (!empty($userUnitsId)) {
            $adminUserId = array_column($userUnitsId, 'adminUserId');
            $adminUserId = array_diff($adminUserId, $hisUser);
            $hisUser = array_merge($hisUser, $adminUserId);
            if (!empty($adminUserId)) {
                foreach ($adminUserId as $v) {
                    $data = ['attendancegroupId' => $id, 'adminUserId' => $v];
                    $adminUserIdgroupId->insert($data);
                }
            }
        }
        $UnitId = $units->selectOne(['parentId' => $UnitsId], 'id');
        if (!empty($UnitId)) {
            $adminUserId = $authuserunits->select('unitsId=' . $UnitId['id'], 'adminUserId')->items;
            $userid = empty($adminUserId) ? [0] : array_column($adminUserId, 'adminUserId');
            self::userUnitsAssoc($id, $UnitId['id'], $userid, $hisUser);
        }
        return true;
    }
    /**
     * 添加考勤组
     * @param AttendanceGroupDTO $attendancegroup
     * @return ResultDO
     */
    public function addAttendanceGroup(AttendanceGroupDTO $attendancegroup)
    {
        $result = new ResultDO();
        $data = $attendancegroup->data;
        $globals = new service_globals();
        //        $result->success = true;
        //        $result->code = 0;
        try {
            $title = $data['title'];
            $setholidaysId = $data['setholidaysId'];
            $platformId = $data['platformId'];
            $goDaysNum = $globals->object_to_array(json_decode($data['goDaysNum']));
            //['num'=>1,'row'=>['one'=>['startTime'=>123123123,'endTime'=>123123123]]]
            $unusualStatus = $globals->object_to_array(json_decode($data['unusualStatus']));
            //异常定义 ['beLate'=>[30,60],'leaveEarly'=>[30,60]]
            $coordinateName = $globals->object_to_array(json_decode($data['coordinateName']));
            //签到地点标题 ['重庆市重庆市九龙坡区']
            $coordinateTitle = $globals->object_to_array(json_decode($data['coordinateTitle']));
            //签到地点名 ['重庆市重庆市九龙坡区']
            $coordinateDeviation = $globals->object_to_array(json_decode($data['coordinateDeviation']));
            //签到范围  ['500']
            $coordinate = $globals->object_to_array(json_decode($data['coordinate']));
            //签到点坐标 ['{"lng":106.482009,"lat":29.516761}']
            $groupNotUser = $globals->object_to_array(json_decode($data['groupNotUser']));
            //['units'=>[1,2,3],'userid'=>[3,5,6]]
            $groupMustUser = $globals->object_to_array(json_decode($data['groupMustUser']));
            //['units'=>[1,2,3],'userid'=>[3,5,6]]
            $approvalProcessOne = $data['approvalProcessOne'];
            $approvalProcessTwo = $data['approvalProcessTwo'];
            $approvalProcessThree = $data['approvalProcessThree'];
            $offDutyOut = $data['offDutyOut'];
            //下班是否需要打卡 1打卡 2不打卡
            $faceStatus = $data['faceStatus'];
            $trackLocation = $data['trackLocation'];
            $type = $data['type'];
            $unitId = $data['unitId'];
            $adminUserId = $data['adminUserId'];
			//判断其他考勤组是否添加单位或者人员 如果有添加则不能修改或者添加考勤组
			$isRepetitionGroupUser = $this->getIsRepetitionGroupUser($groupMustUser, $groupNotUser,0);
            if (!empty($isRepetitionGroupUser[0])){
                $result->code = 400;
                $result->success = true;
                $result->message = $isRepetitionGroupUser[0];
                return $result;
            }elseif(!empty($isRepetitionGroupUser[1])){
                $result->code = 400;
                $result->success = true;
                $result->message = $isRepetitionGroupUser[1];
                return $result;
            }

            // 参数处理 start
            //签到点坐标
            $rule = array();
            //规则
            for ($i = 0; $i < count($coordinateTitle); $i++) {
                $deviation = is_numeric($coordinateDeviation[$i]) ? number_format($coordinateDeviation[$i], 2, '.', '') : 1500;
                if ($deviation > 99000 || $deviation == 0) {
                    $deviation = 99900.0;
                }
                //                    $deviation = $deviation*1000;
                $coordinateDeviation[$i] = $deviation;
                $addcoordinate = htmlspecialchars_decode($coordinate[$i]);
                $rule[] = ['title' => $coordinateTitle[$i], 'deviation' => $coordinateDeviation[$i], 'name' => $coordinateName[$i], 'coordinate' => json_decode($addcoordinate, true)];
            }
            $coordinateS = serialize($rule);
            if ($type == 1) {
                //上下班次数
                $goDaysNum = serialize($goDaysNum);
                //异常定义
                $unusualStatus = serialize($unusualStatus);
                /*****************/
                $row = ['title' => $title, 'setholidaysId' => $setholidaysId, 'platformId' => $platformId, 'goDaysNum' => $goDaysNum, 'unusualStatus' => $unusualStatus, 'groupMustUser' => serialize($groupMustUser), 'groupNotUser' => serialize($groupNotUser), 'coordinate' => $coordinateS, 'approvalProcessOne' => $approvalProcessOne, 'approvalProcessTwo' => $approvalProcessTwo, 'approvalProcessThree' => $approvalProcessThree, 'offDutyOut' => $offDutyOut, 'faceStatus' => $faceStatus, 'trackLocation' => $trackLocation, 'createTime' => time()];
                if( $unitId){
                    $row['unitId'] = $unitId;
                }
            } else {
                /*****************/
                $row = ['title' => $title, 'platformId' => $platformId, 'coordinate' => $coordinateS, 'faceStatus' => $faceStatus, 'type' => 2, 'createTime' => time()];
            }
            $attendancegroupModel = new model_attendance_attendancegroup();
            $id = $attendancegroupModel->insert($row);
            if ($id) {
                $units = new model_lhbase_units();
                $UnitsId = $units->selectOne("id = {$unitId}", 'parentId');
                $this->userUnitsAssoc($id, $UnitsId['parentId'], [$adminUserId]);
                $this->changeGroupUnitIdsUserIds($id, $groupMustUser, $groupNotUser);
                if ($type == 1) {
                    $this->disposeGroupUserMemberArr($id, $platformId, $groupMustUser, $groupNotUser, $title, $setholidaysId, $goDaysNum);
                }
                $result->code = 200;
                $result->success = true;
                $result->message = '数据添加成功';
            } else {
                $result->code = 400;
                $result->success = true;
                $result->message = '数据添加失败';
            }
            return $result;
        } catch (Exception $e) {
            $result->success = false;
            $result->code = 0;
            $result->message = '未知错误';
        }
        return $result;
    }
    /**
     * 修改考勤组
     * @param AttendanceGroupDTO $attendancegroup
     * @return ResultDO
     */
    public function editAttendanceGroup(AttendanceGroupDTO $attendancegroup)
    {
        $result = new ResultDO();
        $serviceGlobals = new service_globals();
        $data = $attendancegroup->data;
        $id = $attendancegroup->id ? $serviceGlobals->getStr($attendancegroup->id) : 0;
        $globals = new service_globals();
        //        $result->success = true;
        //        $result->code = 0;
        try {
            $title = $data['title'];
            $setholidaysId = $data['setholidaysId'];
            $platformId = $data['platformId'];
            $goDaysNum = $globals->object_to_array(json_decode($data['goDaysNum']));
            //['num'=>1,'row'=>['one'=>['startTime'=>123123123,'endTime'=>123123123]]]
            $unusualStatus = $globals->object_to_array(json_decode($data['unusualStatus']));
            //异常定义 ['beLate'=>[30,60],'leaveEarly'=>[30,60]]
            $coordinateTitle = $globals->object_to_array(json_decode($data['coordinateTitle']));
            //签到地点名 ['重庆市重庆市九龙坡区']
            $coordinateName = $globals->object_to_array(json_decode($data['coordinateName']));
            //签到地点标题 ['重庆市重庆市九龙坡区']
            $coordinateDeviation = $globals->object_to_array(json_decode($data['coordinateDeviation']));
            //签到范围  ['500']
            $coordinate = $globals->object_to_array(json_decode($data['coordinate']));
            //签到点坐标 ['{"lng":106.482009,"lat":29.516761}']
            $groupNotUser = $globals->object_to_array(json_decode($data['groupNotUser']));
            //['units'=>[1,2,3],'userid'=>[3,5,6]]
            $groupMustUser = $globals->object_to_array(json_decode($data['groupMustUser']));
            //['units'=>[1,2,3],'userid'=>[3,5,6]]
            $approvalProcessOne = $data['approvalProcessOne'];
            $approvalProcessTwo = $data['approvalProcessTwo'];
            $approvalProcessThree = $data['approvalProcessThree'];
            $offDutyOut = $data['offDutyOut'];
            //下班是否需要打卡 1打卡 2不打卡
            $faceStatus = $data['faceStatus'];
            $trackLocation = $data['trackLocation'];
            $type = $data['type'];
            $adminUserId = $data['adminUserId'];
            $unitId = $data['unitId'];

            //判断其他考勤组是否添加单位或者人员 如果有添加则不能修改或者添加考勤组
            $isRepetitionGroupUser = $this->getIsRepetitionGroupUser($groupMustUser, $groupNotUser,$id);
            if (!empty($isRepetitionGroupUser[0])){
                $result->code = 400;
                $result->success = true;
                $result->message = $isRepetitionGroupUser[0];
                return $result;
            }elseif(!empty($isRepetitionGroupUser[1])){
                $result->code = 400;
                $result->success = true;
                $result->message = $isRepetitionGroupUser[1];
                return $result;
            }

            // 参数处理 start
            //签到点坐标
            $rule = array();
            //规则
            for ($i = 0; $i < count($coordinateTitle); $i++) {
                $deviation = is_numeric($coordinateDeviation[$i]) ? number_format($coordinateDeviation[$i], 2, '.', '') : 1500;
                if ($deviation > 99000 || $deviation == 0) {
                    $deviation = 99900.0;
                }
                //                    $deviation = $deviation*1000;
                $coordinateDeviation[$i] = $deviation;
                $addcoordinate = htmlspecialchars_decode($coordinate[$i]);
                $rule[] = ['title' => $coordinateTitle[$i], 'name' => $coordinateName[$i], 'deviation' => $coordinateDeviation[$i], 'coordinate' => json_decode($addcoordinate, true)];
            }
            $coordinateS = serialize($rule);
            if ($type == 1) {
                //上下班次数
                $goDaysNum = serialize($goDaysNum);
                //异常定义
                $unusualStatus = serialize($unusualStatus);
                /*****************/
                $row = ['title' => $title, 'setholidaysId' => $setholidaysId, 'platformId' => $platformId, 'goDaysNum' => $goDaysNum, 'unusualStatus' => $unusualStatus, 'groupMustUser' => serialize($groupMustUser), 'groupNotUser' => serialize($groupNotUser), 'coordinate' => $coordinateS, 'approvalProcessOne' => $approvalProcessOne, 'approvalProcessTwo' => $approvalProcessTwo, 'approvalProcessThree' => $approvalProcessThree, 'offDutyOut' => $offDutyOut, 'faceStatus' => $faceStatus, 'trackLocation' => $trackLocation, 'createTime' => time()];
            } else {
                /*****************/
                $row = ['title' => $title, 'platformId' => $platformId, 'coordinate' => $coordinateS, 'faceStatus' => $faceStatus, 'type' => 2, 'createTime' => time()];
            }
            $attendancegroupModel = new model_attendance_attendancegroup();
            $attendancegroupModel->update(" id = {$id} ", $row);
            if ($id) {
                $this->changeGroupUnitIdsUserIds($id, $groupMustUser, $groupNotUser);
                if ($type == 1) {
                    $this->disposeGroupUserMemberArr($id, $platformId, $groupMustUser, $groupNotUser, $title, $setholidaysId, $goDaysNum);
                }
                $result->code = 200;
                $result->success = true;
                $result->message = "数据修改成功";
            } else {
                $result->code = 400;
                $result->success = true;
                $result->message = '数据修改失败';
            }
            return $result;
        } catch (Exception $e) {
            $result->success = false;
            $result->code = 0;
            $result->message = '未知错误';
        }
        return $result;
    }
    /**
     * 操作考勤组
     * @param AttendanceGroupDTO $attendancegroup
     * @return ResultDO
     */
    public function operationAttendanceGroup(AttendanceGroupDTO $attendancegroup)
    {
        $result = new ResultDO();
        $data = $attendancegroup->data;
        $id = $attendancegroup->id ? getStr($attendancegroup->id) : 0;
        $globals = new service_globals();
        //        $result->success = true;
        //        $result->code = 0;
        try {
            $title = $data['title'];
            $do = $data['do'];
            $setholidaysId = $data['setholidaysId'];
            $platformId = $data['platformId'];
            $goDaysNum = $globals->object_to_array(json_decode($data['goDaysNum']));
            //['num'=>1,'row'=>['one'=>['startTime'=>123123123,'endTime'=>123123123]]]
            $unusualStatus = $globals->object_to_array(json_decode($data['unusualStatus']));
            //异常定义 ['beLate'=>[30,60],'leaveEarly'=>[30,60]]
            $coordinateTitle = $globals->object_to_array(json_decode($data['coordinateTitle']));
            //签到地点名 ['重庆市重庆市九龙坡区']
            $coordinateDeviation = $globals->object_to_array(json_decode($data['coordinateDeviation']));
            //签到范围  ['500']
            $coordinate = $globals->object_to_array(json_decode($data['coordinate']));
            //签到点坐标 ['{"lng":106.482009,"lat":29.516761}']
            $groupNotUser = $globals->object_to_array(json_decode($data['groupNotUser']));
            //['units'=>[1,2,3],'userid'=>[3,5,6]]
            $groupMustUser = $globals->object_to_array(json_decode($data['groupMustUser']));
            //['units'=>[1,2,3],'userid'=>[3,5,6]]
            $approvalProcessOne = $data['approvalProcessOne'];
            $approvalProcessTwo = $data['approvalProcessTwo'];
            $approvalProcessThree = $data['approvalProcessThree'];
            $offDutyOut = $data['offDutyOut'];
            //下班是否需要打卡 1打卡 2不打卡
            $faceStatus = $data['faceStatus'];
            $trackLocation = $data['trackLocation'];
            $type = $data['type'];
            //              $adminUserId = $data['adminUserId'];
            // 参数处理 start
            //签到点坐标
            $rule = array();
            //规则
            for ($i = 0; $i < count($coordinateTitle); $i++) {
                $deviation = is_numeric($coordinateDeviation[$i]) ? number_format($coordinateDeviation[$i], 2, '.', '') : 1500;
                if ($deviation > 99000 || $deviation == 0) {
                    $deviation = 99900.0;
                }
                //                    $deviation = $deviation*1000;
                $coordinateDeviation[$i] = $deviation;
                $addcoordinate = htmlspecialchars_decode($coordinate[$i]);
                $rule[] = ['title' => $coordinateTitle[$i], 'deviation' => $coordinateDeviation[$i], 'coordinate' => json_decode($addcoordinate, true)];
            }
            $coordinateS = serialize($rule);
            if ($type == 1) {
                //上下班次数
                $goDaysNum = serialize($goDaysNum);
                //异常定义
                $unusualStatus = serialize($unusualStatus);
                /*****************/
                $row = ['title' => $title, 'setholidaysId' => $setholidaysId, 'platformId' => $platformId, 'goDaysNum' => $goDaysNum, 'unusualStatus' => $unusualStatus, 'groupMustUser' => serialize($groupMustUser), 'groupNotUser' => serialize($groupNotUser), 'coordinate' => $coordinateS, 'approvalProcessOne' => $approvalProcessOne, 'approvalProcessTwo' => $approvalProcessTwo, 'approvalProcessThree' => $approvalProcessThree, 'offDutyOut' => $offDutyOut, 'faceStatus' => $faceStatus, 'trackLocation' => $trackLocation, 'createTime' => time()];
            } else {
                /*****************/
                $row = ['title' => $title, 'platformId' => $platformId, 'coordinate' => $coordinateS, 'faceStatus' => $faceStatus, 'type' => 2, 'createTime' => time()];
            }
            $attendancegroupModel = new model_attendance_attendancegroup();
            $id = $attendancegroupModel->update($row, " id = {$id} ");
            if ($id) {
                if ($type == 1) {
                    $this->disposeGroupUserMemberArr($id, $platformId, $groupMustUser, $groupNotUser, $title, $setholidaysId, $goDaysNum);
                }
                $result->code = 1;
                $result->success = true;
                $result->message = 1;
            } else {
                $result->code = 0;
                $result->success = true;
                $result->message = '数据添加失败';
            }
            return $result;
        } catch (Exception $e) {
            $result->success = false;
            $result->code = 0;
            $result->message = '未知错误';
        }
        return $result;
    }
    /**
     * 删除考勤组
     * @param AttendanceGroupDTO $attendancegroup
     * @return ResultDO
     */
    public function deleteAttendanceGroup(AttendanceGroupDTO $attendancegroup)
    {
        $id = $attendancegroup->id ? gdl_lib_BaseUtils::getStr($attendancegroup->id) : 0;
        $result = new ResultDO();
        $result->success = true;
        $result->message = "您已删除，请勿重复操作";
        $result->code = 400;
        $result->data = [];
        //        if(empty($platformId)){
        //            $result->message = "您还没有选择平台";
        //            return $result;
        //        }
        if (empty($id)) {
            $result->message = "参数错误";
            return $result;
        }
        try {
            $attendancegroupModel = new model_attendance_attendancegroup();
            $where = " id = {$id} ";
            $res = $attendancegroupModel->update($where, " isDelete=1");
            if ($res) {
                $result->code = 200;
                $result->message = "已删除";
            }
        } catch (Exception $e) {
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage();
        }
        return $result;
    }
    /**
     * 处理添加或者修改时 考勤组人员的变更
     * @param $agid
     * @param $platformId
     * @param $groupMustUser
     * @param $groupNotUser
     * @return bool
     */
    public function disposeGroupUserMemberArr($agid, $platformId, $groupMustUser, $groupNotUser, $agName, $setholidaysId, $goDaysNum)
    {
        $id = $agid;
        //考勤组ID
        $rowNums = 0;
        //总人数
        $attendanceGroupUserModel = new model_attendance_attendancegroupuser();
        $memberModel = new model_attendance_member();
        //参与考勤人员 ['units'=>[1,2,3],'userid'=>[3,5,6]]
        $useridsMustAll = '';
        //获取选择的人员ID
        if (!empty($groupMustUser['userid'])) {
            $useridsMust = implode(',', $groupMustUser['userid']);
            $useridsMustAll = $useridsMust;
        }

        //根据架构获取所有人员
        if (!empty($groupMustUser['units'])) {
            $unitsMust = implode(',', $groupMustUser['units']);
            $memberCondition = " unitid in ({$unitsMust}) and status=2 ";
            $mustMemberids = $memberModel->select($memberCondition, 'id')->items;
            $mustMemberids = $mustMemberids ? implode(',', array_column($mustMemberids, 'id')) : "";
            $useridsMustAll = !empty($useridsMustAll) ? ($mustMemberids ? $useridsMustAll . ',' . $mustMemberids : $useridsMustAll) : $mustMemberids;
        }
        //考勤组人员档案表
        $groupmemberrecordModel = new model_attendance_groupmemberrecord();
        $setholidaysModel = new model_attendance_setholidays();
        $setholidaysRow = $setholidaysModel->selectOne(" id = {$setholidaysId} ", 'workday,specialWorkday,holiday');
		$aaUserIds  = $useridsMustAll;
		//排除每个架构中 和 选定的人员中已经参加考勤组的人员 并踢出之前的考勤组
        $groupMustCondition = " platformId ={$platformId}  and memberId in ({$useridsMustAll}) and type = 1 ";
        $sureMustMemberids = $attendanceGroupUserModel->select($groupMustCondition, 'id')->items;
        if (!empty($sureMustMemberids)) {
            $attendanceGroupUserModel->delete("agId={$id} and  type =1 and status=0 ");
            $sureMustMemberids = implode(',', array_column($sureMustMemberids, 'id'));
            $attendanceGroupUserModel->delete(" id in ({$sureMustMemberids}) ");
        }
        $useridsMustAll = explode(',', $useridsMustAll);
        $rowNums = $rowNums + count(array_unique(array_filter($useridsMustAll)));

        foreach ($useridsMustAll as $userVar) {
            $attendanceGroupUserModel->insert(['agId' => $id, 'memberId' => $userVar, 'type' => 1, 'platformId' => $platformId, 'createTime' => time(), 'status' => 0]);
        }
        //无需考勤人员
        $useridsNotAll = '';
        //获取选择的人员ID
        if (!empty($groupNotUser['userid'])) {
            $useridsNot = implode(',', $groupNotUser['userid']);
            $useridsNotAll = $useridsNot;
        }
        //根据架构获取所有人员
        if (!empty($groupNotUser['units'])) {
            $unitsNot = implode(',', $groupNotUser['units']);
            $memberCondition = " unitid in ({$unitsNot})   and status=2 ";
            $notMemberids = $memberModel->select($memberCondition, 'id')->items;
            $notMemberids = $notMemberids ? implode(',', array_column($notMemberids, 'id')) : "";
            $useridsNotAll = !empty($useridsNotAll) ? $notMemberids ? $useridsNotAll . ',' . $notMemberids : $useridsNotAll : $notMemberids;
        }
		$mmUseridsAll = '';
		if(empty($aaUserIds)){
					$mmUseridsAll =$useridsNotAll;
		}else{
			if(!empty($useridsNotAll)){
				$mmUseridsAll =$aaUserIds.",".$useridsNotAll;
			}else{
				$mmUseridsAll = $aaUserIds;
			}
		}

        //查询节假日定义
        $groupmemberrecordModel->insert(['memberIds' => $mmUseridsAll, 'agId' => $id, 'addTime' => time(), 'agName' => $agName, 'status' => 1, 'date' => date('Y-m-d', time()), 'workday' => $setholidaysRow['workday'], 'specialWorkday' => $setholidaysRow['specialWorkday'], 'holiday' => $setholidaysRow['holiday'], 'goDaysNum' => $goDaysNum]);
       
        //排除每个架构中 和 选定的人员中已经无需参加考勤组的人员 并踢出之前的考勤组
        $groupNotCondition = " platformId ={$platformId}  and memberId in ({$useridsNotAll}) and type = 2 ";
        $sureNotMemberids = $attendanceGroupUserModel->select($groupNotCondition, 'id')->items;
        if (!empty($sureNotMemberids)) {
            $attendanceGroupUserModel->delete("agId={$id} and  type =2 and status=0 ");
            $sureNotMemberids = implode(',', array_column($sureNotMemberids, 'id'));
            $attendanceGroupUserModel->delete(" id in ({$sureNotMemberids}) ");
        }
        $useridsNotAll = explode(',', $useridsNotAll);
        $rowNums = $rowNums + count(array_unique(array_filter($useridsNotAll)));;
        foreach ($useridsNotAll as $userVar) {
            $attendanceGroupUserModel->insert(['agId' => $id, 'memberId' => $userVar, 'type' => 2, 'platformId' => $platformId, 'createTime' => time(), 'status' => 0]);
        }
        $attendancegroupModel = new model_attendance_attendancegroup();
        $attendancegroupModel->update(['id' => $id], ['number' => $rowNums]);
        return true;
    }
    //储存修改考勤组和单位、人员的关系
    private function changeGroupUnitIdsUserIds($agId, $groupMustUser, $groupNotUser)
    {
        if (!$agId) {
            return false;
        }
        $groupunituser = new model_attendance_groupunituser();
        $mustUnitids = implode(',', $groupMustUser['units']);
        $mustUserids = implode(',', $groupMustUser['userid']);
        $notUnitids = implode(',', $groupNotUser['units']);
        $notUserids = implode(',', $groupNotUser['userid']);
        //查找之前考勤组是否有相同单位ID和人员ID 有的话删除
        //type:1需参与考勤  2不需参与考勤 status:1单位 2人员
        $groupunituser->delete(" agId={$agId} ");
        $groupunituser->delete(" status=1 and unitId in ({$mustUnitids}) and type=1  ");
        $groupunituser->delete(" status=2 and memberId in ({$mustUserids}) and type=1  ");
        $groupunituser->delete(" status=1 and unitId in ({$notUnitids}) and type=2  ");
        $groupunituser->delete(" status=2 and memberId in ({$notUserids}) and type=2  ");
        foreach ($groupMustUser['units'] as $key => $value) {
            $data = [
                'agId'=>$agId,
                'status'=>1,
                'type'=>1,
                'unitId'=>$value,
            ];
            $groupunituser->insert($data);
        }
        foreach ($groupMustUser['userid'] as $key => $value) {
            $data = [
                'agId'=>$agId,
                'status'=>2,
                'type'=>1,
                'memberId'=>$value,
            ];
            $groupunituser->insert($data);
        }
        foreach ($groupNotUser['units'] as $key => $value) {
            $data = [
                'agId'=>$agId,
                'status'=>1,
                'type'=>2,
                'unitId'=>$value,
            ];
            $groupunituser->insert($data);
        }
        foreach ($groupNotUser['userid'] as $key => $value) {
            $data = [
                'agId'=>$agId,
                'status'=>2,
                'type'=>2,
                'memberId'=>$value,
            ];
            $groupunituser->insert($data);
        }
        return true;
    }
    //考勤组列表
    public function getAdminAttendanceGroupList(AttendanceGroupDTO $attendancegroup)
    {
        #接受参数
        $data = $attendancegroup->data ? gdl_lib_BaseUtils::getStr($attendancegroup->data) : "";
        $offset = $attendancegroup->offset ? gdl_lib_BaseUtils::getStr($attendancegroup->offset, 'int') : 0;
        $num = $attendancegroup->num ? gdl_lib_BaseUtils::getStr($attendancegroup->num, 'int') : 10;
        $result = new ResultDO();
        $result->success = true;
        $result->code = 400;
        $result->data = [];
        #验证
        if (empty($data)) {
            $result->message = "缺少必要条件";
            return $result;
        }
        $platformId = $data['platformId'] ? $data['platformId'] : 0;
        $adminUserId = $data['adminUserId'] ? $data['adminUserId'] : 0;
        $adminReg = $data['adminReg'] ? $data['adminReg'] : '';
        #条件
        $where = " platformId ={$data['platformId']} AND isdelete = 0  ";
        if (isset($data['type']) && $data['type'] == 1) {
            $where .= " AND type = {$data['type']} ";
        } elseif (isset($data['type']) && $data['type'] == 2) {
            $where .= " AND type = {$data['type']} ";
        } else {
            $where .= " AND type = 1 ";
        }
        if (isset($data['title']) && !empty($data['title'])) {
            $where .= " AND title like '%{$data['title']}%' ";
        }
        if (isset($data['departmenName']) && !empty($data['departmenName'])) {
            $where .= " AND departmenName like '%{$data['departmenName']}%' ";
        }
        if (isset($data['unitId']) && !empty($data['unitId'])) {
            $where .= " AND unitId = {$data['unitId']} ";
        }
        //根据管理员ID获取所有单位ID
        $userServiceModel = new service_user();
        $globalsModel = new service_globals();
        $unitIdsList = $userServiceModel->getMemberUnitsRelation($platformId, $adminUserId, 2);
        if ($unitIdsList['relation']) {
            $unitIdsList['relation'] = $globalsModel->setArrKeyId($unitIdsList['relation']);
        }
        $groupunituser = new model_attendance_groupunituser();
        $appadminuser = new model_lhbase_appadminuser();
        $appadminuserInfo = $appadminuser->selectOne("id={$adminUserId} and characters='zg' and unitsId=0");
        //        print_r($adminUserId);die;
        if (!$appadminuserInfo) {
            $adminUserIdgroupId = new model_attendance_adminuserattendancegroup();
            $attendancegroupIds = $adminUserIdgroupId->select(" adminUserId = {$adminUserId} ", 'attendancegroupId')->items;
            if ($attendancegroupIds) {
                $attendancegroupIds = array_column($attendancegroupIds, 'attendancegroupId');
                $attendancegroupIds = implode(',', $attendancegroupIds);
                $where .= " and id in ({$attendancegroupIds}) ";
            } else {
                $result->message = "暂无数据";
                $result->code = 200;
                $result->data = [];
                $result->counts = 0;
                return $result;
            }
        }
        #分页
        if ($offset == '0') {
            $offset = 1;
        }
        $limit = ($offset - 1) * $num . "," . $num;
        $group = 'order by id desc limit ' . $limit;
        $count = 0;
        try {
            $List = [];
            #数据
            $attendancegroupModel = new model_attendance_attendancegroup();
            $groupFiled = "id,title,number,groupMustUser,platformId,unitId";
            $join = "";
            if ($data['status'] == 1) {
                //  1只返回考勤组名称 2只返回单位名称 3只返回组织名称列表
                $groupFiled = "id,title";
                $group = '';
            }
            if (isset($data['id']) && !empty($data['id'])) {
                $where .= " AND id = {$data['id']}";
                $groupFiled = "atd_attendance_group.*";
            }
            $groupWhere = $where;
            $List = $attendancegroupModel->select($groupWhere, $groupFiled, $group, "", $join)->items;

            $count = $attendancegroupModel->selectOne($groupWhere, "count(id) num");
            $count = !empty($count['num']) ? $count['num'] : 0;
            if ($data['status'] == 2) {
                // 1只返回考勤组名称 2只返回单位名称 3只返回组织名称列表
                //                if (!$appadminuserInfo){
                //                    $condition = "";
                //                }else{
                //                    $condition = "";
                //                }
                //                $groupunituser->select($condition);
            } elseif ($data['status'] == 3) {
            }
            if ($List) {
                #数据
                /****获取单位名字*****/
                $unitsModel = new model_lhbase_units();
                foreach ($List as &$oo) {
                    $unit_name = $unitsModel->selectOne(['id' => $oo['unitId']], 'unitName');
                    $oo['unitName'] = $unit_name['unitName'];
                }
            }
            if (isset($List[0]['groupMustUser'])) {
                foreach ($List as &$value) {
                    $coordinateUnitName = '';
                    $groupMustUser = ['units' => array(), 'userid' => array()];
                    $groupNotUser = ['units' => array(), 'userid' => array()];
                    $unituserList = $groupunituser->select(" agId = {$value['id']} ")->items;
                    foreach ($unituserList as $uulV) {
                        if ($uulV['type'] == 1 and $uulV['status'] == 1) {
                            $groupMustUser['units'][] = $uulV['unitId'];
                        } elseif ($uulV['type'] == 1 and $uulV['status'] == 2) {
                            $groupMustUser['userid'][] = $uulV['memberId'];
                        } elseif ($uulV['type'] == 2 and $uulV['status'] == 1) {
                            $groupNotUser['units'][] = $uulV['unitId'];
                        } elseif ($uulV['type'] == 2 and $uulV['status'] == 2) {
                            $groupNotUser['userid'][] = $uulV['memberId'];
                        }
                    }
                    foreach ($groupMustUser['units'] as $unkey => $unV) {
                        $op = "/";
                        if (count($groupMustUser['units']) - 1 == $unkey || count($groupMustUser['units']) == 1) {
                            $op = '';
                        }
                        $coordinateUnitName .= isset($unitIdsList['relation'][$unV]) ? $unitIdsList['relation'][$unV]['title'] . $op : '本单位' . $op;
                    }
                    $value['groupMustUser'] = serialize($groupMustUser);
                    $value['groupNotUser'] = serialize($groupNotUser);
                    $value['coordinateUnitName'] = $coordinateUnitName;
                }
            }
            # 处理数据
            if ($List) {
                $result->message = "获取成功";
                $result->code = 200;
                $result->data = $List;
            } else {
                $result->message = "暂无数据";
            }
        } catch (Exception $ex) {
            $result->message = $ex->getMessage();
        }
        $result->counts = $count;
        return $result;
    }
    /**
     * 获取当前用户上面有几级
     */
    public function getPlatformManagementLevel(AttendanceGroupDTO $attendancegroup)
    {
        #接受参数
        $data = $attendancegroup->data ? gdl_lib_BaseUtils::getStr($attendancegroup->data) : "";
        $result = new ResultDO();
        $result->success = true;
        $result->code = 400;
        $result->data = [];
        #验证
        $platformId = $data['platformId'] ? $data['platformId'] : 0;
        $unitId = $data['unitId'] ? $data['unitId'] : 0;
        if (empty($platformId)) {
            $result->message = "缺少必要条件";
            return $result;
        }
        //        if(empty($unitid)){$result->message = "缺少必要条件"; return $result;}
        try {
            $List = [];
            #数据
            $memberModel = new model_attendance_member();
            $unitsModel = new model_lhbase_units();
            $uLevel = $unitsModel->selectOne("id = {$unitId}   and isDelete=1 ", 'level');
            $level = $unitsModel->selectOne(" platformId='{$platformId}'  and isDelete=1", "id,level", 'order by level desc');
            //获取低于当前层级的数据
            //
            $num = $level['level'] - $uLevel['level'];
            for ($i = 0; $i <= $num; $i++) {
                $status = 2;
                //1无主管 2有主管
                //                $isCh = $memberModel->selectOne("unitId= {$value['id']} and status=2 and isCharge=1 ");
                //                if ($isCh) $status = 2;//1无主管 2有主管
                $List[$i] = ['name' => "第" . ($i + 1) . "级主管", "level" => $i + 1, "status" => $status, "type" => "target_management"];
//                if ($i == 0) {
//                    $List[$i] = ['name' => "直接主管", "level" => 1, "status" => $status, "type" => "target_management"];
//                } else {
//                    $List[$i] = ['name' => "第" . ($i + 1) . "级主管", "level" => $i + 1, "status" => $status, "type" => "target_management"];
//                }
            }
            # 处理数据
            if ($List) {
                #数据
                $result->message = "获取成功";
                $result->code = 200;
                $result->data = $List;
            } else {
                $result->message = "暂无数据";
            }
        } catch (Exception $ex) {
            $result->message = $ex->getMessage();
        }
        return $result;
    }
	
	//判断其他考勤组是否添加单位或者人员
	 public function getIsRepetitionGroupUser($groupMustUser, $groupNotUser,$agId){
        $unMsg = "";
        $userMsg = "";
        $unitsModel = new model_lhbase_units();
        $groupunituser =  new model_attendance_groupunituser();
        //参与考勤人员 ['units'=>[1,2,3],'userid'=>[3,5,6]]
        $useridsMustAll = '';
        //获取选择的人员ID
        if (!empty($groupMustUser['userid'])) {
            $useridsMust = implode(',', $groupMustUser['userid']);
            $memberCondition = "aag.isDelete= 0 and atd_attendance_group_unit_user.memberId in ({$useridsMust}) and  atd_attendance_group_unit_user.status=2";
            if ($agId){
                $memberCondition .=" and atd_attendance_group_unit_user.agId<>$agId ";
            }
            $join = array(
                "atd_attendance_group aag"=>"aag.id=atd_attendance_group_unit_user.agId",
                "atd_member am"=>"am.id=atd_attendance_group_unit_user.memberId",
            );
            $mustUnits = $groupunituser->select(
                $memberCondition,
                'atd_attendance_group_unit_user.id,atd_attendance_group_unit_user.agId,am.realName,aag.title',
                "",
                "",$join)->items;

            foreach ($mustUnits as  $mUk=>$mUv){
                $userMsg .= "考勤组{$mUv['title']}已经存在人员{$mUv['realName']};";
            }
        }
		//根据架构获取所有人员
        if (!empty($groupMustUser['units'])) {
            $unitsMust = implode(',', $groupMustUser['units']);
            $memberCondition = "aag.isDelete= 0 and  atd_attendance_group_unit_user.unitId in ({$unitsMust}) and atd_attendance_group_unit_user.status=1 ";
            if ($agId){
                $memberCondition .=" and atd_attendance_group_unit_user.agId<>$agId ";
            }
            $join = array(
                "atd_attendance_group aag"=>"aag.id=atd_attendance_group_unit_user.agId",
            );
            $mustUnits = $groupunituser->select(
                $memberCondition,
                'atd_attendance_group_unit_user.id,atd_attendance_group_unit_user.agId,atd_attendance_group_unit_user.unitId,aag.title',
                "",
                "",$join)->items;

            foreach ($mustUnits as  $mUk=>$mUv){
                $unitName = $unitsModel->selectOne(" id ={$mUv['unitId']}",'unitName');
                $unitName = $unitName?$unitName['unitName']:'';
                $unMsg .= "考勤组{$mUv['title']}已经存在单位{$unitName};";
            }
         }

         if (!empty($groupNotUser['userid'])) {
             $useridsMust = implode(',', $groupNotUser['userid']);
             $memberCondition = "aag.isDelete= 0 and  atd_attendance_group_unit_user.memberId in ({$useridsMust}) and atd_attendance_group_unit_user.status=2 ";
             if ($agId){
                 $memberCondition .=" and atd_attendance_group_unit_user.agId<>$agId ";
             }
             $join = array(
                 "atd_attendance_group aag"=>"aag.id=atd_attendance_group_unit_user.agId",
                 "atd_member am"=>"am.id=atd_attendance_group_unit_user.memberId",
             );
             $mustUnits = $groupunituser->select(
                 $memberCondition,
                 'atd_attendance_group_unit_user.id,atd_attendance_group_unit_user.agId,am.realName,aag.title',
                 "",
                 "",$join)->items;

             foreach ($mustUnits as  $mUk=>$mUv){
                 $userMsg .= "考勤组{$mUv['title']}已经存在人员{$mUv['realName']};";
             }
         }
         //根据架构获取所有人员
         if (!empty($groupNotUser['units'])) {
             $unitsMust = implode(',', $groupNotUser['units']);
             $memberCondition = "aag.isDelete= 0 and  atd_attendance_group_unit_user.unitId in ({$unitsMust}) and atd_attendance_group_unit_user.status=1 ";
             if ($agId){
                 $memberCondition .=" and atd_attendance_group_unit_user.agId<>$agId ";
             }
             $join = array(
                 "atd_attendance_group aag"=>"aag.id=atd_attendance_group_unit_user.agId",
             );
             $mustUnits = $groupunituser->select(
                 $memberCondition,
                 'atd_attendance_group_unit_user.id,atd_attendance_group_unit_user.agId,atd_attendance_group_unit_user.unitId,aag.title',
                 "",
                 "",$join)->items;

             foreach ($mustUnits as  $mUk=>$mUv){
                 $unitName = $unitsModel->selectOne(" id ={$mUv['unitId']}",'unitName');
                 $unitName = $unitName?$unitName['unitName']:'';
                 $unMsg .= "考勤组{$mUv['title']}已经存在单位{$unitName};";
             }
         }
         return [$unMsg,$userMsg];
	}
}